
import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View,
  Dimensions,TouchableOpacity,SafeAreaView,StatusBar,
  Image,ScrollView
} from 'react-native';
import {connect} from 'react-redux';
import Swiper from 'react-native-swiper';
//import {getUser} from '../../actions/user'
import VideoCenter from '../../component/VideoCenter'
import BottomView from '../../component/BottomView'
import SearchView from '../../component/SearchView'
import { TipModal } from '../../component/Tips';
import {jumpPage} from '../../common/common'
import {BASEURL} from '../../api/api';
import Search from '../Templ/Search';
import DeviceStorage from '../../common/DeviceStorage';
var IMG_URL =  BASEURL+'image/showImage?imageName=';
const {height, width} = Dimensions.get('window');

class Home extends Component {
  static navigationOptions = ({ navigation }) =>{
    return{
      header:null,
    }
  };
  constructor(props){
    super(props);
    this.state = ({
      selectHy:'默认',
      gridData:[],
      searchVal:'',
      refreshList: [],
      videoList: [],
      recommendList:[],
      userId:'',
    })
  }
  componentWillMount(){
    //this.props.dispatch(getUser())
    DeviceStorage.get('user').then((user)=>{
      if(user){
        let userInfo = JSON.parse(user);
        this.setState({
          userId: userInfo.userId
        })
      } 
    })
  }
  componentDidMount(){
    this._getTempTypeList();
    this._getRefreshList();
  }
  _getTempTypeList(){
    this.refs.tipModal._loading();
    fetch(BASEURL+'home/getTempType?showInHome=1')
    .then(res=>res.json())
    .then(result=>{
      this.refs.tipModal._close();
      //console.log(result);
      if(result.succ == '1'){
        this.setState({
          gridData: result.list,
        })
      }
    })
  }
  _getRefreshList(){
    fetch(BASEURL+'home/getRefreshList')
    .then(res=>res.json())
    .then(result=>{
      this.refs.tipModal._close();
      //console.log(result);
      if(result.succ == '1'){
        this.setState({
          videoList: result.videoList,
          refreshList: result.refreshList,
          recommendList: result.recommendList,
        })
      }
    })
  }
  _goTo(item){
		if(item.typeName =='全部' ){
			this.props.navigation.navigate('Template');
		} else {
			jumpPage(this.props.navigation,'typeList',{typeId: item.tempTypeId,typeName: item.typeName})
		}
    
    // if(this.props.navigation){
    //   this.props.navigation.push('typeList',{typeId: index,typeName: text});
    // }
  }
  _typeSelect(){
    if(this.props.navigation){
      this.props.navigation.push('typeSelect',{
        callback: (data)=>{
          this.setState({
            selectHy:data.text,
          })
        }
      });
    }
  }
  videoMore(){
    this._typeSelect();
  }
  refreshMore(){
    this._typeSelect();
  }
  _renderMenu(){
    // const dataArr = [
    //   {text: '贺卡', img: require('../../images/heka.png')},
    //   {text: '邀请函', img: require('../../images/yaoqinghan.png')},
    //   {text: '相册', img: require('../../images/xiangce.png')},
    //   {text: '婚礼', img: require('../../images/hunli.png')},
    //   {text: '促销', img: require('../../images/cuxiao.png')},
    //   {text: '新品上新', img: require('../../images/xinpinshangxin.png')},
    //   {text: '旅行', img: require('../../images/lvxing.png')},
    //   {text: '生日', img: require('../../images/shengri.png')},
    //   {text: '招聘', img: require('../../images/zhaopin.png')},
    //   {text: '更多', img: require('../../images/gengduo.png')},
    // ]
    const dataArr = this.state.gridData;
    let list = [];
    for(var i=0; i<dataArr.length ;i++){
      let item = dataArr[i];
      //console.log(IMG_URL+item.typeIcon)
      list.push(
        <TouchableOpacity style={styles.menuView} key={i} onPress={()=>this._goTo(item)}>
          <Image style={styles.menuIcon} source={{uri: IMG_URL+item.typeIcon}}/>
          <Text style={styles.menuText}>{item.typeName}</Text>
        </TouchableOpacity>
      );
    }
    return list;
  }
  _search(){
    //this.refs.tipModal._loading();
    fetch(BASEURL+'home/getTempType?showInHome=')
    .then(res=>res.json())
    .then(result=>{
      this.refs.tipModal._close();
      //console.log(result);
      //console.log('val',this.state.searchVal)
      if(result.succ == '1'){
        var tempType = result.list.find(item => {
          return item.typeName == this.state.searchVal;
        })
        //console.log('tempType',tempType);
        if(tempType){
          jumpPage(this.props.navigation,'typeList',{typeId: tempType.tempTypeId,typeName: tempType.typeName})
        } else {
          jumpPage(this.props.navigation,'typeList',{typeId: '',typeName: this.state.searchVal})
        }
        // this.setState({
        //   gridData: result.list,
        // })
      }
    })
    
    // if(this.props.navigation){
  }
  _onChange(val){
    this.setState({
      searchVal:val
    })
  }
  render() {
    //console.log('user---',this.props.user);
    const videoData = {
      title:'节日精选>>',
      img:require("../../images/video.png"),
      data: this.state.videoList
      // [
      //   {text: '我和时光都在等',img: require("../../images/group2.png")},
      //   {text: '我和时光都在等',img: require("../../images/group3.png")},
      //   {text: '我和时光都在等',img: require("../../images/group2.png")},
      //   {text: '我和时光都在等',img: require("../../images/group3.png")},
      // ]
    }
    const freshData = {
      title:'最新上线>>',
      img:require("../../images/line.png"),
      data:this.state.refreshList
      // [
      //   {text: '我和时光都在等',img: require("../../images/group4.png")},
      //   {text: '我和时光都在等',img: require("../../images/group5.png")},
      //   {text: '我和时光都在等',img: require("../../images/group2.png")},
      //   {text: '我和时光都在等',img: require("../../images/group3.png")},
      // ]
    }
    const recommendData = {
      title:'精品推荐>>',
      img:require("../../images/line.png"),
      data:this.state.recommendList
    }
    return (
      <SafeAreaView style={{flex:1,marginTop:0,backgroundColor:'#fff'}}>
        <StatusBar hidden={false} backgroundColor='black' barStyle='light-content'/>
        <ScrollView style={styles.container} showsVerticalScrollIndicator={false}>
          <View style={{flexDirection:'row',alignItems:'center',paddingBottom:6}}>
            <TouchableOpacity style={styles.leftBtn} onPress={()=>{this._typeSelect()}}>
              <Text style={styles.leftBtnText}>{this.state.selectHy}</Text>
              <Image style={styles.arrowImg} source={require('../../images/arrow_down.png')}/>
            </TouchableOpacity>
            {/* <SearchView placeholder='搜索你喜欢的' 
              search={()=>this._search()} 
              onBlur={()=>this._search()}
							onChange={(val)=>this._onChange(val)}/> */}
            <Search placeholder='搜索您想要的模板...'
              index={true}
							style={{paddingLeft:10,borderRadius:20,height:40}}
              search={()=>this._search()} 
              subStyle={{backgroundColor:'#f0f0f0',marginTop:5,paddingRight:5,paddingLeft:5}}
							onChange={(val)=>this._onChange(val)}
            />
          </View>
          <View style={styles.swiper}>
            <Swiper style={styles.wrapper} showsButtons={false} autoplay={true} height={150}>
              <View style={styles.slide}>
                <Image resizeMode='stretch' style={styles.swiperImg} source={require('../../images/a_1.jpg')}/>
              </View>
              <View style={styles.slide}>
                <Image resizeMode='stretch' style={styles.swiperImg} source={require('../../images/a_2.png')}/>
              </View>
              <View style={styles.slide}>
                <Image resizeMode='stretch' style={styles.swiperImg} source={require('../../images/a_3.jpg')}/>
              </View>
            </Swiper>
          </View>
          <View style={styles.splitView}></View>
          <View style={styles.middleMenu}>
              {this._renderMenu()}
          </View>
          <View style={styles.splitView}></View>
          <VideoCenter data={videoData} userId={this.state.userId} imgW={23} press={()=>this.videoMore()} navigation={this.props.navigation}/>
          <View style={styles.splitView}></View>
          <VideoCenter data={freshData} userId={this.state.userId} imgW={4} press={()=>this.refreshMore()} navigation={this.props.navigation}/>
          <View style={styles.splitView}></View>
          <VideoCenter data={recommendData} userId={this.state.userId} imgW={4} press={()=>this.refreshMore()} navigation={this.props.navigation}/>
          {/*<BottomView color='#999' bgColor='#eee' lineColor='#ccc' text="已经到底啦"/>*/}
          <TipModal ref="tipModal"/>
        </ScrollView>
      </SafeAreaView>
    );
  }
}

const styles = StyleSheet.create({
  leftBtnText:{
    fontSize:14,
    color:'#888',
    marginRight:5,
  },  
  leftBtn:{
    marginLeft:20,
    flexDirection:'row',
    justifyContent:'center',
    alignItems:'center',
  },
  arrowImg:{
    width:20,
    height:20,
  },  
  splitView:{
    height:10,
    backgroundColor:'#f0f0f0'
  },
  menuText:{
    color:'#333',
    fontSize:13,
    paddingTop:4,
    paddingBottom:4,
  },  
  menuIcon:{
    width:width>500 ? 65 : width/5-20,
    height:width>500 ? 65 : width/5-20,
    resizeMode:'contain',
    // borderWidth:StyleSheet.hairlineWidth,
    // borderColor:'green',
    marginTop:10,
  },  
  middleMenu:{
    flexDirection:'row',
    //换行显示
    flexWrap:'wrap',
    justifyContent:'flex-start',
    alignItems:'center',
  },
  menuView:{
    width:width/4-1,
    justifyContent:'center',
    alignItems:'center',
    // borderWidth:1,
    // borderColor:'red'
  },
  swiperImg:{
    width,
    flex:1,
  },
  slide: {
    flex: 1,
    justifyContent: 'center',
    backgroundColor: 'transparent',
  },
  swiper:{
    height:150,
    width:'100%',
  },
  container: {
    flex: 1,
  },
 
});
export default Home;
//export default connect(state=>state.user)(Home);
